package com.platform.cdcs.fragment;

import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.DocNo;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.tool.ViewTool;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/9/26.
 */
public class TicketChooseFragment extends BaseFragment {

    private ItemAdapter adapter;
    //    private DocNo docNo;
    private String id, cusCode, inNo;
    private ChooseItem currentItem;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
//        docNo = (DocNo) getArguments().getSerializable("model");
//        int pos = getArguments().getInt("pos");
//        docNo.getDocNoList().get(0).setCheck(true);
        id = getArguments().getString("id");
        cusCode = getArguments().getString("cusCode");
        inNo = getArguments().getString("inNo");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initView(View view) {
        adapter = new ItemAdapter(getContext());
        initLoadImg(view.findViewById(R.id.load));
        hideThisToolBar(view);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        setTitle("关联出入库单");
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.ticket_choose, null);
        initLoadImg(view.findViewById(R.id.load));
        ObservableXListView listView = (ObservableXListView) view.findViewById(android.R.id.list);
        listView.setPullRefreshEnable(false);
        listView.addHeaderView(headerView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                DocNo.DocItem item = (DocNo.DocItem) adapterView.getItemAtPosition(i);
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                bundle.putString("cusCode", cusCode);
                bundle.putString("code", item.getDocNo());
                bundle.putString("time", item.getDocDate().substring(0, 10));
                bundle.putString("inNo", inNo);
                FragmentUtil.navigateToInNewActivity(getActivity(), TicketProductFragment.class, bundle);
            }
        });
        requestData();
    }

//    private void removeRelation(ChooseItem item) {
//        showLoadImg();
//        Map<String, String> map = new HashMap<>();
//        map.put("inId", id);
//        map.put("docNo", item.getTitle());
//        getHttpClient().post().url(Constant.CANCEL_INVOICE_PRODUCT).params(Constant.makeParam(map)).build().execute(new StringCallback() {
//
//            @Override
//            public void onError(Call call, Exception e, int i) {
//                dismissLoadImg();
//                Utils.showToast(getContext(), R.string.server_error);
//            }
//
//            @Override
//            public void onResponse(String s, int i) {
//                dismissLoadImg();
//                Type type = new TypeToken<BaseObjResponse<MockObj>>() {
//                }.getType();
//                BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
//                if ("1".equals(response.getResult().getCode())) {
//                    adapter.clear();
//                    adapter.notifyDataSetChanged();
//                    requestData();
//                    RefershEvent event = new RefershEvent();
//                    event.mclass = TicketRelationFragment.class;
//                    EventBus.getDefault().post(event);
//                } else {
//                    Utils.showToast(getContext(), response.getResult().getMsg());
//                }
//            }
//        });
//    }

    private void requestData() {
        showLoadImg();
        Map<String, String> param = new HashMap<>();
        param.put("id", id);
        param.put("cusCode", cusCode);
        //0已经关联 1全部
        param.put("type", "1");
        getHttpClient().post().url(Constant.LIST_FOR_INVOICE).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                Type type = new TypeToken<BaseObjResponse<DocNo>>() {
                }.getType();
                BaseObjResponse<DocNo> response = new Gson().fromJson(s, type);
                if ("1".equals(response.getResult().getCode())) {
                    List<DocNo.DocItem> list = response.getResult().getDocList();
//                    if (list.size() > 0) {
//                        ChooseItem item = new ChooseItem();
//                        item.setTitle("已关联的出入库单");
//                        item.setTime("");
//                        adapter.addItem(item);
//                        List<ChooseItem> unList = new ArrayList<ChooseItem>();
//                        List<ChooseItem> rlist = new ArrayList<ChooseItem>();
//
//                        for (DocNo.DocItem docItem : list) {
//                            if ("1".equals(docItem.getStatus())) {
//                                ChooseItem subItem = new ChooseItem();
//                                subItem.setType(2);
//                                subItem.setTitle(docItem.getDocNo());
//                                subItem.setTime(docItem.getDocDate().substring(0, 10));
//                                subItem.setText("");
//                                unList.add(subItem);
//                            } else {
//                                ChooseItem subItem = new ChooseItem();
//                                subItem.setType(1);
//                                subItem.setTitle(docItem.getDocNo());
//                                subItem.setStatus("取消关联");
//                                subItem.setTime(docItem.getDocDate().substring(0, 10));
//                                rlist.add(subItem);
//                                subItem = new ChooseItem();
//                                subItem.setType(2);
//                                subItem.setTitle(docItem.getDocNo());
//                                subItem.setTime(docItem.getDocDate().substring(0, 10));
//                                subItem.setStatus(docItem.getDocDate().substring(0, 10));
//                                subItem.setText("再次选择，会重新关联所有产品");
//                                unList.add(subItem);
//                            }
//                        }
//                        adapter.addAll(rlist);
//
//                        item = new ChooseItem();
//                        item.setTitle("出入库单号");
//                        item.setTime("单据日期");
//                        adapter.addItem(item);
//                        if (rlist.size() == 1) {
//                            rlist.get(0).setDrawable(1);
//                        } else {
//                            for (int j = 0; j < rlist.size(); j++) {
//                                if (j == 0) {
//                                    rlist.get(j).setDrawable(2);
//                                } else if (j == rlist.size() - 1) {
//                                    rlist.get(j).setDrawable(4);
//                                } else {
//                                    rlist.get(j).setDrawable(3);
//                                }
//                            }
//                        }
//                        adapter.addAll(unList);
//                        adapter.notifyDataSetChanged();
//                    }
                    adapter.addAll(list);
                    adapter.notifyDataSetChanged();
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }
            }
        });
    }

    @Override
    public int layoutId() {
        return R.layout.listview;
    }

//    private void post() {
//        if (currentItem == null) {
//            Utils.showToast(getContext(), "请先选择!");
//            return;
//        }
//        showLoadImg();
//        Map<String, String> map = new HashMap<>();
//        map.put("cusCode", cusCode);
//        map.put("docNo", currentItem.getTitle());
//        map.put("innoId", id);
//        getHttpClient().post().url(Constant.ADD_INVOICE_PRODUCT).params(Constant.makeParam(map)).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int i) {
//                dismissLoadImg();
//                Utils.showToast(getContext(), R.string.server_error);
//            }
//
//            @Override
//            public void onResponse(String s, int i) {
//                dismissLoadImg();
//                Type type = new TypeToken<BaseObjResponse<MockObj>>() {
//                }.getType();
//                BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
//                if ("1".equals(response.getResult().getCode())) {
//                    RefershEvent event = new RefershEvent();
//                    event.mclass = TicketRelationFragment.class;
//                    EventBus.getDefault().post(event);
//                    Utils.showToast(getContext(), "关联成功");
//                    adapter.clear();
//                    adapter.notifyDataSetChanged();
//                    requestData();
//
//                } else {
//                    Utils.showToast(getContext(), response.getResult().getMsg());
//                }
//            }
//        });
//    }

    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == getClass()) {
            getActivity().finish();
        }
    }

    private class ItemAdapter extends EnhancedAdapter<DocNo.DocItem> {

        public ItemAdapter(Context context) {
            super(context);
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            ViewHolder holder = (ViewHolder) paramView.getTag();
            DocNo.DocItem item = getItem(position);
            holder.titleView.setText(item.getDocNo());
            holder.timeView.setText(item.getDocDate().substring(0, 10));
        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            View rootView = null;
            ViewHolder holder = new ViewHolder();
            rootView = inflater.inflate(R.layout.three_item, viewgroup, false);
            holder.titleView = (TextView) rootView.findViewById(R.id.title);
            rootView.findViewById(R.id.text).setVisibility(View.GONE);
            holder.timeView = (TextView) rootView.findViewById(R.id.desc);
            rootView.setTag(holder);
            return rootView;
        }


    }

    private class ViewHolder {
        TextView titleView, timeView;
    }
}
